package com.softme.trade.engine.setup;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SetupEngine
{
	private static final Log log = LogFactory.getLog(SetupEngine.class);

	private static SetupEngine setup;

	private ArrayList<String> setupList;

	private SetupEngine()
	{
		setupList = new ArrayList<String>();

		//aqui faz o mapeamento de setups
		setupList.add(SetupRole.class.getSimpleName());
		setupList.add(SetupUser.class.getSimpleName());
		setupList.add(SetupCurrency.class.getSimpleName());
		//setup de idiomas
		//setup de entradas

	}

	public static SetupEngine getInstance()
	{
		if (setup == null)
			setup = new SetupEngine();
		return setup;
	}

	public static void close()
	{
		getInstance().setupList.clear();
		setup = null;
	}

	public boolean run()
	{
		SetupEngine.log.info("Executing setup...");

		long l1 = System.currentTimeMillis();

		for (String clazz : setupList)
		{
			run(clazz);
		}

		SetupEngine.log.info((System.currentTimeMillis() - l1) + " ms to execute setup.");

		//FIXME - Implementar quais setups são obrigatórios, 
		//			ao qual em caso de erro deve interromper a subida do ambiente
		return true;
	}

	private boolean run(final String clazz)
	{
		try
		{
			Setup setup = (Setup) Class.forName("com.softme.trade.engine.setup." + clazz)
					.newInstance();

			if (setup.canRun())
			{
				if (log.isDebugEnabled())
					log.debug("Executing " + clazz);

				long l1 = System.currentTimeMillis();
				setup.run();

				if (log.isDebugEnabled())
					log.debug(clazz + " executed time: " + (System.currentTimeMillis() - l1) + "ms");
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return true;
	}
}
